package com.example.elmmerchants.Product_Management;

import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.elmmerchants.R;
import com.example.elmmerchants.SQL.Connection_SQL;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Category_Management_Page extends AppCompatActivity {

    LinearLayout push_category_layout, add_category;
    AlertDialog dialog, category_setting_dialog, delete_dialog;
    ProgressBar is_loading_category;

    String email, category;
    String temp = "";
    boolean is_upload = false, is_update = false, is_delete = false;
    Map<String, Integer> category_map = new HashMap<>();

    private class Build_Category extends Thread {

        EditText set_category_name_text;

        public Build_Category(EditText set_category_name_text) {
            this.set_category_name_text = set_category_name_text;
        }

        @Override
        public void run() {
            is_upload = false;
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "update `merchant` set shop_category = ? where email = ?";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, category + set_category_name_text.getText().toString() + ",");
                    preparedStatement.setString(2, email);
                    preparedStatement.executeUpdate();
                    is_upload = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_upload) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    category = category + set_category_name_text.getText().toString() + ",";
                    push_category_layout.removeAllViews();
                    is_loading_category.setVisibility(View.VISIBLE);
                    show_category();
                }
            });
        }
    }

    private class Update_Category extends Thread {

        Dialog dialog1;

        public Update_Category(Dialog dialog1) {
            this.dialog1 = dialog1;
        }

        @Override
        public void run() {
            is_update = false;
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "update `merchant` set shop_category = ? where email = ?";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, category);
                    preparedStatement.setString(2, email);
                    preparedStatement.executeUpdate();
                    is_update = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_update) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    category_map.clear();
                    push_category_layout.removeAllViews();
                    is_loading_category.setVisibility(View.VISIBLE);
                    show_category();
                    dialog1.dismiss();
                }
            });
        }
    }

    private class Delete_Category extends Thread {

        Dialog dialog1;
        TextView category_name;

        public Delete_Category(Dialog dialog1, TextView category_name) {
            this.dialog1 = dialog1;
            this.category_name = category_name;
        }

        @Override
        public void run() {
            is_delete = false;
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL connectionSql = new Connection_SQL();
                    Connection connection = connectionSql.connection();

                    String sql2 = "update `merchant` set shop_category = ?";
                    PreparedStatement preparedStatement2 = connection.prepareStatement(sql2);
                    preparedStatement2.setString(1, category);
                    preparedStatement2.executeUpdate();
                    is_delete = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_delete) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    category_map.clear();
                    push_category_layout.removeAllViews();
                    is_loading_category.setVisibility(View.VISIBLE);
                    show_category();
                    dialog1.dismiss();
                }
            });
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_category_management_page);

        email = getIntent().getStringExtra("email");
        category = getIntent().getStringExtra("category");

        push_category_layout = findViewById(R.id.push_category_layout);
        add_category = findViewById(R.id.add_category);
        is_loading_category = findViewById(R.id.is_loading_category);

        add_category.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                View view1 = LayoutInflater.from(view.getContext()).inflate(R.layout.add_category_view, null);
                EditText set_category_name_text = view1.findViewById(R.id.set_category_name_text);
                TextView text_length = view1.findViewById(R.id.text_length);
                text_length.setText(String.valueOf(set_category_name_text.length()));
                set_category_name_text.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    }

                    @Override
                    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void afterTextChanged(Editable editable) {
                        text_length.setText(String.valueOf(set_category_name_text.getText().length()));
                    }
                });
                AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                builder.setTitle("设置名称");
                builder.setView(view1);
                builder.setPositiveButton("建立", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (set_category_name_text.getText().toString().isEmpty()) {
                            Toast.makeText(Category_Management_Page.this, "请先设置名称", Toast.LENGTH_SHORT).show();
                        }
                        else if (category_map.containsKey(set_category_name_text.getText().toString())) {
                            Toast.makeText(Category_Management_Page.this, "请勿设置相同名称", Toast.LENGTH_SHORT).show();
                        }
                        else {
                            Build_Category buildCategory = new Build_Category(set_category_name_text);
                            buildCategory.start();
                        }
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });
                builder.setCancelable(false);

                dialog = builder.create();
                dialog.show();
            }
        });

        show_category();
    }

    void show_category() {
        is_loading_category.setVisibility(View.GONE);
        for (int i = 0; i < category.length(); i++) {
            if (category.charAt(i) == ',') {
                if (!temp.equals("全部") && !temp.equals("未分类")) {
                    category_map.put(temp, 1);
                    View view = LayoutInflater.from(this).inflate(R.layout.category_management_card_view, null);
                    TextView category_name = view.findViewById(R.id.category_name);
                    category_name.setText(temp);
                    LinearLayout setting = view.findViewById(R.id.setting);
                    setting.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Dialog dialog1 = new Dialog(view.getContext());
                            dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
                            dialog1.setContentView(R.layout.set_category_setting_view);
                            LinearLayout update_name = dialog1.findViewById(R.id.update_name);
                            update_name.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    View view1 = LayoutInflater.from(view.getContext()).inflate(R.layout.category_setting_alertdialog_view, null);
                                    EditText set_category_name_text = view1.findViewById(R.id.set_category_name_text);
                                    set_category_name_text.setText(category_name.getText());
                                    TextView text_length = view1.findViewById(R.id.text_length);
                                    text_length.setText(String.valueOf(set_category_name_text.length()));
                                    set_category_name_text.addTextChangedListener(new TextWatcher() {
                                        @Override
                                        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                                        }

                                        @Override
                                        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                                        }

                                        @Override
                                        public void afterTextChanged(Editable editable) {
                                            text_length.setText(String.valueOf(set_category_name_text.getText().length()));
                                        }
                                    });
                                    AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                                    builder.setTitle("修改名称");
                                    builder.setView(view1);
                                    builder.setPositiveButton("修改", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            if (set_category_name_text.getText().toString().isEmpty()) {
                                                Toast.makeText(Category_Management_Page.this, "请设置名称", Toast.LENGTH_SHORT).show();
                                            }
                                            else if (set_category_name_text.getText().toString().equals(category_name.getText())) {
                                                Toast.makeText(Category_Management_Page.this, "请修改名称", Toast.LENGTH_SHORT).show();
                                            }
                                            else {
                                                category_map.replace(set_category_name_text.getText().toString(), 1);
                                                category = "全部,未分类,";
                                                for (String key : category_map.keySet()) {
                                                    if (!key.equals("全部") && !key.equals("未分类")){
                                                        if (key.equals(category_name.getText().toString())) {
                                                            category += set_category_name_text.getText().toString();
                                                            category += ",";
                                                        }
                                                        else {
                                                            category += key;
                                                            category += ",";
                                                        }
                                                    }
                                                }
                                                Update_Category updateCategory = new Update_Category(dialog1);
                                                updateCategory.start();
                                            }
                                        }
                                    });
                                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {

                                        }
                                    });
                                    builder.setCancelable(false);

                                    category_setting_dialog = builder.create();
                                    category_setting_dialog.show();
                                }
                            });
                            LinearLayout delete = dialog1.findViewById(R.id.delete);
                            delete.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                                    builder.setTitle("是否刪除分类");
                                    builder.setMessage("是否刪除" + category_name.getText() + "分类");
                                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            category = "全部,未分类,";
                                            for (String key : category_map.keySet()) {
                                                if (!key.equals("全部") && !key.equals("未分类") && !key.equals(category_name.getText().toString())){
                                                    category += key;
                                                    category += ",";
                                                }
                                            }

                                            Delete_Category deleteCategory = new Delete_Category(dialog1, category_name);
                                            deleteCategory.start();
                                        }
                                    });
                                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {

                                        }
                                    });
                                    builder.setCancelable(false);

                                    delete_dialog = builder.create();
                                    delete_dialog.show();
                                }
                            });
                            LinearLayout cancel = dialog1.findViewById(R.id.cancel);
                            cancel.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    dialog1.dismiss();
                                }
                            });

                            dialog1.show();
                            dialog1.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                            dialog1.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                            dialog1.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
                            dialog1.getWindow().setGravity(Gravity.BOTTOM);
                        }
                    });
                    push_category_layout.addView(view);
                }
                temp = "";
            }
            else {
                temp += category.charAt(i);
            }
        }
    }
}